package edu.jinghuan.lms.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.jinghuan.lms.entity.Borrow;
import edu.jinghuan.lms.entity.dto.BorrowWithRemainingDaysDTO;
import edu.jinghuan.lms.service.IBorrowService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/borrows")
@RequiredArgsConstructor
public class BorrowController {
    private final IBorrowService borrowService;

    @PostMapping
    public ResponseEntity<?> add(@RequestBody Borrow borrow) {
        if (borrowService.save(borrow)) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.badRequest().body("图书不存在或已全部借出");
        }
    }

    @PutMapping("/{id}/return")
    public ResponseEntity<?> returnBook(@PathVariable Long id) {
        Borrow borrow = new Borrow();
        borrow.setId(id);
        borrow.setStatus("RETURNED");
        borrow.setReturnTime(LocalDateTime.now());
        
        if (borrowService.updateById(borrow)) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.badRequest().body("借阅记录不存在");
        }
    }

    @GetMapping
    public Page<BorrowWithRemainingDaysDTO> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String bookName,
            @RequestParam(required = false) String borrower,
            @RequestParam(required = false) String status) {
        
        LambdaQueryWrapper<Borrow> queryWrapper = new LambdaQueryWrapper<>();
        
        // 只有当参数不为空且不为空字符串时才添加条件
        if (status != null && !status.trim().isEmpty()) {
            queryWrapper.eq(Borrow::getStatus, status);
        }
        if (borrower != null && !borrower.trim().isEmpty()) {
            queryWrapper.like(Borrow::getBorrower, borrower);
        }
        if (bookName != null && !bookName.trim().isEmpty()) {
            queryWrapper.like(Borrow::getBookId, bookName);
        }
        
        // 按创建时间倒序排序
        queryWrapper.orderByDesc(Borrow::getCreateTime);
        
        return borrowService.pageWithRemainingDays(new Page<>(page, size), queryWrapper);
    }
}
